#pragma once
#include "Connection.hpp"
#include <string>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "Comm.hpp"
#include "Log.hpp"
#include <errno.h>
#include <cstring>
#include <functional>
#include "HandlerConnection.hpp"
#include "SetNonBlock.hpp"
class Accepter
{
public:                                              // 写成一个函数就可以了
    static void AccepterConnection(Connection *conn) // 专门给listen用的
    {
        while (true)
        {
            errno = 0;
            struct sockaddr_in addr;
            memset(&addr, 0, sizeof addr);
            socklen_t len = sizeof addr;
            int clientfd = accept(conn->GetSockfd(), CONV(&addr), &len);
            if (clientfd >= 0)
            {
                // 注册好了
                //  func_t recver = std::bind(&HandlerConnection::Recver, std::placeholders::_1);    //这里不需要bind
                //  func_t sender = std::bind(&HandlerConnection::Sender, std::placeholders::_1);
                //  func_t excepter = std::bind(&HandlerConnection::Excepter, std::placeholders::_1);
                // 创建出来了
                Connection *clientconn = ConnectionFactory::CreateNormalConnection(clientfd, EPOLLIN | EPOLLET, conn->_R,
                                                                                   HandlerConnection::Recver,
                                                                                   HandlerConnection::Sender,
                                                                                   HandlerConnection::Excepter,
                                                                                   addr);
                // 非阻塞下
                SetNonBlock(clientfd);
                conn->_R->AddConnction(clientconn);
                lg.LogMessage(Info, "客户端链接已经被TcpServer管理, fd:%d\n", clientfd);
            }
            else
            {
                
                if(errno == EAGAIN)
                {
                    lg.LogMessage(Warning, "发送缓冲区满了\n");
                    break;
                }
                else if(errno == EINTR)
                    lg.LogMessage(Warning, "被信号中断");
                else
                {
                    lg.LogMessage(Error, "出错或者对端关闭, errno:%d:%s\n", errno, strerror(errno));
                    break;
                }
            }
        }
    }
};